//
//  forwardCommandVC.m
//  SQLiteTesting
//
//  Created by kitinat on 2/13/13.
//  Copyright (c) 2013 EGA. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "EGAAppDelegate.h"
#import "forwardCommandVC.h"
#import "UIViewController+MJPopupViewController.h"
#import "whoWillBeAbleToCommand.h"
#import "taskListDetailVC.h"
#import "EGAUtility.h"

@interface forwardCommandVC ()

@end

@implementation forwardCommandVC

@synthesize ClosebookOrForward;
@synthesize CommandToWho;
@synthesize btnChooseNextCommand;
@synthesize btnForward;
@synthesize btnCloseBook;
@synthesize tfDescription;
@synthesize DocID;
@synthesize EmpID;

//@synthesize EmpToID;


NSMutableString * EmpToID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setviewLoading];
    [tfDescription becomeFirstResponder];
    [self setTextViewAsTextField];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [tfDescription resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}








-(void)setviewLoading
{
    viewLoading = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];    
    viewLoading.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.25];    
    UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((self.view.frame.size.width/2) - 60, (self.view.frame.size.height/2) - 40, 150, 120)];
    activityIndicator.backgroundColor=[UIColor colorWithRed:105/255.0 green: 105/255.0 blue:105/255.0 alpha:1];
    [activityIndicator layer].cornerRadius = 8.0;
    [activityIndicator startAnimating];
    [viewLoading addSubview:activityIndicator];
    
    UILabel * activityLabel = [[UILabel alloc] init];
    activityLabel.text = NSLocalizedString(@"Loading..", @"string1");
    activityLabel.textColor = [UIColor whiteColor];
    activityLabel.font = [UIFont boldSystemFontOfSize:20];
    activityLabel.backgroundColor=[UIColor clearColor];
    activityLabel.frame=CGRectMake((self.view.frame.size.width/2) - 60, (self.view.frame.size.height/2) , 150, 100);
    activityLabel.textAlignment = UITextAlignmentCenter;
    [viewLoading addSubview:activityLabel];
    
    [self.view addSubview:viewLoading];
    [self hideLoadingView];
}


-(void)showLoadingView
{
    [self.view.superview insertSubview:viewLoading aboveSubview:self.view];
}

-(void)hideLoadingView
{
    [viewLoading performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
}

-(void)setTextViewAsTextField
{
    tfDescription.layer.cornerRadius = 10;
    [tfDescription.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
    [tfDescription.layer setBorderWidth:2.0];
    tfDescription.clipsToBounds = YES;
}














- (IBAction)btnCloseBookTouch:(id)sender {
    ClosebookOrForward = [[NSString alloc]init];
    ClosebookOrForward = @"CloseBook";
    
    UIImage *image = [UIImage imageNamed:@"bt_circleClick.png"]; //the radioButton image when selected
    [btnCloseBook setBackgroundImage:image forState:UIControlStateNormal];
    [btnCloseBook setBackgroundImage:image forState:UIControlStateSelected];
    [btnCloseBook setBackgroundImage:image forState:UIControlStateHighlighted];
    
    UIImage *image2 = [UIImage imageNamed:@"bt_circle.png"]; //the radioButton image when selected
    [btnForward setBackgroundImage:image2 forState:UIControlStateNormal];
    [btnForward setBackgroundImage:image2 forState:UIControlStateSelected];
    [btnForward setBackgroundImage:image2 forState:UIControlStateHighlighted];
    
    btnChooseNextCommand.hidden = YES;
}

- (IBAction)btnForwardTouch:(id)sender {
    ClosebookOrForward = [[NSString alloc]init];
    ClosebookOrForward = @"Forward";
    
    UIImage *image = [UIImage imageNamed:@"bt_circle.png"]; //the radioButton image when selected
    [btnCloseBook setBackgroundImage:image forState:UIControlStateNormal];
    [btnCloseBook setBackgroundImage:image forState:UIControlStateSelected];
    [btnCloseBook setBackgroundImage:image forState:UIControlStateHighlighted];
    
    UIImage *image2 = [UIImage imageNamed:@"bt_circleClick.png"]; //the radioButton image when selected
    [btnForward setBackgroundImage:image2 forState:UIControlStateNormal];
    [btnForward setBackgroundImage:image2 forState:UIControlStateSelected];
    [btnForward setBackgroundImage:image2 forState:UIControlStateHighlighted];
    
    btnChooseNextCommand.hidden = NO;
}

- (IBAction)btnChooseNextCommandTouch:(id)sender {
    whoWillBeAbleToCommand *FCVC = [[whoWillBeAbleToCommand alloc] initWithNibName:@"whoWillBeAbleToCommand" bundle:nil];
    FCVC.DocID = DocID;
    FCVC.EmpID = EmpID;
    FCVC.delegate = self;
    [self presentPopupViewController:FCVC animationType:0 popupType:@"commandWho"];

}

- (IBAction)btnCommandTouch:(id)sender
{
    


    
    
    
    
    
    
    
    
    
    
    
    
    
    [NSThread detachNewThreadSelector:@selector(showLoadingView) toTarget:self withObject:nil ];
    sleep(2.0);
    
    
    
    NSString *post;
    
    if (tfDescription.text != (id)[NSNull null] && tfDescription.text.length != 0 )
    {
        NSString * postTextUTF8 = [tfDescription.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if ([ClosebookOrForward isEqualToString:@"CloseBook"])
        {
            post = [NSString stringWithFormat:@"documentListID=%@&TransferRecieve=%@&TaskType=%@&Description=%@",
                    DocID,EmpID,@"1",postTextUTF8];
        }
        else if ([ClosebookOrForward isEqualToString:@"Forward"])
        {
            post = [NSString stringWithFormat:@"documentListID=%@&TransferRecieve=%@&TransferTo=%@&TaskType=%@&Description=%@",
                    DocID,EmpID,EmpToID,@"0",postTextUTF8];
            
        }
    }
    
    //test send command
    //NSString *strRequest=[NSString stringWithFormat:@"http://%@TaskAction.ashx",serviceUrl];
    
    //NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strRequest]];
    
//    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//    
//    [request setHTTPMethod:@"POST"];
//    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [request setHTTPBody:postData];
//    //request and get response status
//    NSData * dataReturn =     [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
    
    /////////////////new
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString *strURL=[NSString stringWithFormat:@"ws=TaskAction.ashx&%@",post];
    NSData *dataReturn =[Util getDataFromService:strURL];
    /////////////////new
    
    
    
    
    
    
    NSArray * returnDict = [NSJSONSerialization JSONObjectWithData:dataReturn options:kNilOptions error:nil];
    NSString *returnStatus = [returnDict[0] objectForKey:@"Status"];
    
    if([returnStatus isEqualToString:@"True"])
    {
        if([_delegate respondsToSelector:@selector(didCloseOrCommand)])
        {
            [_delegate didCloseOrCommand];
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"สำเร็จ"
                                                        message:@"สั่งการ/ปิดเรื่องเรียบร้อยแล้ว"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"มีความผิดพลาดบางประการ"
                                                        message:@"ทำให้ไม่สามารถสั่งการ/ปิดเรื่องได้"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
    
    
    

    [self hideLoadingView];
    
    
    
    
    
    
    
    
    
    
    
    
    

}








//delegate method
-(void)choosenWhoWithID:(NSString*)choosenEmpID choosenEmpName:(NSString*)choosenEmpName
{
    EmpToID = [[NSMutableString alloc]initWithString:choosenEmpID];
    //EmpToID = choosenEmpID;
    [btnChooseNextCommand setTitle:choosenEmpName forState:UIControlStateNormal];
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}










- (void)dealloc {
    [super dealloc];
}
@end
